<template>
  <div class="management-system-container">
    <!-- 统计概览 -->
    <div class="overview-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="overview-content">
              <div class="overview-icon total">
                <el-icon>
                  <Document />
                </el-icon>
              </div>
              <div class="overview-info">
                <div class="overview-number">{{ statistics.total }}</div>
                <div class="overview-label">制度总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="overview-content">
              <div class="overview-icon active">
                <el-icon>
                  <CircleCheck />
                </el-icon>
              </div>
              <div class="overview-info">
                <div class="overview-number">{{ statistics.active }}</div>
                <div class="overview-label">生效中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="overview-content">
              <div class="overview-icon draft">
                <el-icon>
                  <Edit />
                </el-icon>
              </div>
              <div class="overview-info">
                <div class="overview-number">{{ statistics.draft }}</div>
                <div class="overview-label">草稿</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="overview-content">
              <div class="overview-icon expired">
                <el-icon>
                  <Clock />
                </el-icon>
              </div>
              <div class="overview-info">
                <div class="overview-number">{{ statistics.expired }}</div>
                <div class="overview-label">已过期</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 查询表单 -->
    <el-card shadow="never" style="margin-bottom: 8px">
      <el-form :model="queryForm" :inline="true" label-width="80px">
        <el-form-item label="制度名称">
          <el-input v-model="queryForm.name" placeholder="请输入制度名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="制度类型">
          <el-select v-model="queryForm.type" placeholder="请选择类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="管理制度" value="management" />
            <el-option label="技术规范" value="technical" />
            <el-option label="操作规程" value="operation" />
            <el-option label="安全制度" value="safety" />
            <el-option label="质量标准" value="quality" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="生效中" value="active" />
            <el-option label="草稿" value="draft" />
            <el-option label="已过期" value="expired" />
            <el-option label="已废止" value="abolished" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="queryForm.createTimeRange" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
            style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon>
              <Search />
            </el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card shadow="never" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增制度</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" @click="handleBatchDelete"
            :disabled="!selectedRows.length">批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="Upload" @click="handleImport">导入制度</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Download" @click="handleExport">导出数据</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Refresh" @click="handleRefresh">刷新</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="DataAnalysis" @click="handleSystemAnalysis">制度分析</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table ref="tableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
        v-loading="loading" border>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="制度名称" width="200" show-overflow-tooltip />
        <el-table-column prop="code" label="制度编号" width="150" />
        <el-table-column prop="type" label="制度类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)" size="small">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="版本号" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="effectiveDate" label="生效日期" width="120" />
        <el-table-column prop="expiryDate" label="失效日期" width="120" />
        <el-table-column prop="department" label="归属部门" width="120" show-overflow-tooltip />
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" icon="View" @click="handleView(row)">查看</el-button>
            <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="warning" icon="Management" @click="handleVersion(row)">版本管理</el-button>
            <el-button link type="info" icon="CopyDocument" @click="handleCopy(row)">复制</el-button>
            <el-dropdown @command="(command) => handleMoreAction(command, row)">
              <el-button link type="primary">
                更多<el-icon class="el-icon--right">
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="publish" :disabled="row.status === 'active'">
                    发布
                  </el-dropdown-item>
                  <el-dropdown-item command="abolish" :disabled="row.status === 'abolished'">
                    废止
                  </el-dropdown-item>
                  <el-dropdown-item command="archive">
                    归档
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <Pagination :total="pagination.total" v-model:page="pagination.currentPage" v-model:limit="pagination.pageSize"
          @pagination="handlePagination" />
      </div>
    </el-card>

    <!-- 制度表单对话框 -->
    <SystemFormDialog v-model:visible="formDialogVisible" :system-data="currentSystem" @success="handleFormSuccess" />

    <!-- 制度详情对话框 -->
    <SystemDetailDialog v-model:visible="detailDialogVisible" :system-data="currentSystem" @edit="handleEdit" />

    <!-- 版本管理对话框 -->
    <SystemVersionDialog v-model:visible="versionDialogVisible" :system-data="currentSystem"
      @success="handleFormSuccess" />

    <!-- 制度分析对话框 -->
    <SystemAnalysisDialog v-model:visible="analysisDialogVisible" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Clock,
  Search,
  Refresh,
  Plus,
  Delete,
  Upload,
  Download,
  DataAnalysis,
  ArrowDown,
  View,
  Edit,
  Management,
  CopyDocument
} from '@element-plus/icons-vue'
import SystemFormDialog from './components/SystemFormDialog.vue'
import SystemDetailDialog from './components/SystemDetailDialog.vue'
import SystemVersionDialog from './components/SystemVersionDialog.vue'
import SystemAnalysisDialog from './components/SystemAnalysisDialog.vue'
import Pagination from '@/components/Pagination/index.vue'

// 表格引用
const tableRef = ref()

// 加载状态
const loading = ref(false)

// 统计数据
const statistics = reactive({
  total: 156,
  active: 128,
  draft: 15,
  expired: 13
})

// 查询表单
const queryForm = reactive({
  name: '',
  type: '',
  status: '',
  createTimeRange: []
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 选中的行
const selectedRows = ref([])

// 对话框显示状态
const formDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const versionDialogVisible = ref(false)
const analysisDialogVisible = ref(false)

// 当前操作的制度
const currentSystem = ref({})

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const types: Record<string, string> = {
    management: 'primary',
    technical: 'success',
    operation: 'warning',
    safety: 'danger',
    quality: 'info'
  }
  return types[type] || 'primary'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const texts: Record<string, string> = {
    management: '管理制度',
    technical: '技术规范',
    operation: '操作规程',
    safety: '安全制度',
    quality: '质量标准'
  }
  return texts[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const types: Record<string, string> = {
    active: 'success',
    draft: 'info',
    expired: 'warning',
    abolished: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    active: '生效中',
    draft: '草稿',
    expired: '已过期',
    abolished: '已废止'
  }
  return texts[status] || status
}

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 表格数据
const tableData = ref([
  {
    id: 1,
    name: '水库安全管理制度',
    code: 'GLZD-001',
    type: 'safety',
    version: 'V2.1',
    status: 'active',
    effectiveDate: '2024-01-01',
    expiryDate: '2025-12-31',
    department: '安全管理部',
    creator: '张三',
    createTime: '2024-01-01 09:00:00',
    description: '规范水库日常安全管理工作的各项制度和流程'
  },
  {
    id: 2,
    name: '水位监测技术规范',
    code: 'GLZD-002',
    type: 'technical',
    version: 'V1.5',
    status: 'active',
    effectiveDate: '2024-01-15',
    expiryDate: '2024-12-31',
    department: '技术部',
    creator: '李四',
    createTime: '2024-01-10 14:30:00',
    description: '水位监测设备的技术标准和操作规范'
  },
  {
    id: 3,
    name: '应急预案管理办法',
    code: 'GLZD-003',
    type: 'management',
    version: 'V3.0',
    status: 'draft',
    effectiveDate: '',
    expiryDate: '',
    department: '应急管理部',
    creator: '王五',
    createTime: '2024-01-20 10:15:00',
    description: '应急预案的制定、修订、演练和评估管理办法'
  },
  {
    id: 4,
    name: '设备维护操作规程',
    code: 'GLZD-004',
    type: 'operation',
    version: 'V2.0',
    status: 'active',
    effectiveDate: '2023-06-01',
    expiryDate: '2024-05-31',
    department: '设备部',
    creator: '赵六',
    createTime: '2023-05-20 16:45:00',
    description: '各类设备的日常维护和保养操作规程'
  },
  {
    id: 5,
    name: '质量控制标准',
    code: 'GLZD-005',
    type: 'quality',
    version: 'V1.0',
    status: 'expired',
    effectiveDate: '2023-01-01',
    expiryDate: '2023-12-31',
    department: '质量部',
    creator: '孙七',
    createTime: '2022-12-15 11:20:00',
    description: '工程质量控制的各项标准和要求'
  }
])

// 统一的模拟数据源与筛选分页逻辑
const allData = ref<any[]>([])

const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
const randomChoice = <T>(arr: T[]): T => arr[randInt(0, arr.length - 1)]
const pad2 = (n: number) => (n < 10 ? `0${n}` : `${n}`)
const formatISODate = (d: Date) => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`
const formatISODateTime = (d: Date) => `${formatISODate(d)} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`

const generateMockData = () => {
  if (allData.value.length) return
  const types = ['management', 'technical', 'operation', 'safety', 'quality']
  const statuses = ['active', 'draft', 'expired', 'abolished']
  const departments = ['安全管理部', '技术部', '设备部', '质量部', '应急管理部', '行政部']
  const creators = ['张三', '李四', '王五', '赵六', '孙七', '周八']
  const totalCount = randInt(10, 50)
  const count = Math.max(totalCount - tableData.value.length, 0)
  const base: any[] = []
  for (let i = 0; i < count; i++) {
    const created = new Date(2023, randInt(0, 11), randInt(1, 28), randInt(8, 18), randInt(0, 59), randInt(0, 59))
    const effective = new Date(2023 + randInt(0, 1), randInt(0, 11), randInt(1, 28))
    const expiry = new Date(effective)
    expiry.setFullYear(effective.getFullYear() + randInt(0, 2))
    base.push({
      id: i + 100,
      name: `制度-${i + 1}`,
      code: `GLZD-${pad2(i + 1)}`,
      type: randomChoice(types),
      version: `V${randInt(1, 3)}.${randInt(0, 9)}`,
      status: randomChoice(statuses),
      effectiveDate: formatISODate(effective),
      expiryDate: randomChoice([formatISODate(expiry), '']),
      department: randomChoice(departments),
      creator: randomChoice(creators),
      createTime: formatISODateTime(created),
      updateTime: formatISODateTime(created),
      description: '示例制度说明内容'
    })
  }
  // 将页面内初始数据并入
  allData.value = [...tableData.value, ...base]
}

const applyFiltersAndPaginate = () => {
  let data = [...allData.value]
  // 名称
  if (queryForm.name?.trim()) {
    const kw = queryForm.name.trim().toLowerCase()
    data = data.filter(item => `${item.name}`.toLowerCase().includes(kw))
  }
  // 类型
  if (queryForm.type) {
    data = data.filter(item => item.type === queryForm.type)
  }
  // 状态
  if (queryForm.status) {
    data = data.filter(item => item.status === queryForm.status)
  }
  // 创建时间范围
  if (Array.isArray(queryForm.createTimeRange) && queryForm.createTimeRange.length === 2) {
    const [start, end] = queryForm.createTimeRange
    const startDate = new Date(start + ' 00:00:00').getTime()
    const endDate = new Date(end + ' 23:59:59').getTime()
    data = data.filter(item => {
      const ts = new Date(item.createTime).getTime()
      return ts >= startDate && ts <= endDate
    })
  }
  // 更新统计
  const total = data.length
  statistics.total = allData.value.length
  statistics.active = allData.value.filter(i => i.status === 'active').length
  statistics.draft = allData.value.filter(i => i.status === 'draft').length
  statistics.expired = allData.value.filter(i => i.status === 'expired').length

  pagination.total = total
  const startIdx = (pagination.currentPage - 1) * pagination.pageSize
  tableData.value = data.slice(startIdx, startIdx + pagination.pageSize)
}

// 查询
const handleQuery = () => {
  loading.value = true
  setTimeout(() => {
    pagination.currentPage = 1
    applyFiltersAndPaginate()
    loading.value = false
    if (pagination.total === 0) {
      ElMessage.info('未找到符合条件的数据')
    } else {
      ElMessage.success(`查询到 ${pagination.total} 条记录`)
    }
  }, 300)
}

// 重置
const handleReset = () => {
  queryForm.name = ''
  queryForm.type = ''
  queryForm.status = ''
  queryForm.createTimeRange = []
  pagination.currentPage = 1
  loadTableData()
  ElMessage.info('查询条件已重置')
}

// 分页处理
const handlePagination = (pager: any) => {
  pagination.currentPage = pager.page
  pagination.pageSize = pager.limit
  loadTableData()
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    generateMockData()
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确认删除制度"${row.name}"？删除后将无法恢复。`, 
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    // 从全量数据中移除
    const idx = allData.value.findIndex(item => item.id === row.id)
    if (idx !== -1) allData.value.splice(idx, 1)

    // 重新应用筛选与分页
    applyFiltersAndPaginate()

    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先选择要删除的数据')
    return
  }
  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedRows.value.length} 条制度记录？删除后将无法恢复。`,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    const ids = selectedRows.value.map(r => r.id)
    allData.value = allData.value.filter(item => !ids.includes(item.id))
    selectedRows.value = []
    applyFiltersAndPaginate()
    ElMessage.success(`成功删除 ${ids.length} 条记录`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败，请重试')
    }
  }
}

// 表单成功回调
const handleFormSuccess = (data: any) => {
  if (data) {
    if (data.id && allData.value.find(item => item.id === data.id)) {
      const index = allData.value.findIndex(item => item.id === data.id)
      if (index !== -1) {
        allData.value[index] = { ...data }
      }
    } else {
      const newId = Date.now()
      allData.value.unshift({ ...data, id: newId, createTime: formatISODateTime(new Date()) })
    }
  }
  applyFiltersAndPaginate()
}

// 页面挂载
onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
.management-system-container {
  padding: 20px;
}

.overview-section {
  margin-bottom: 20px;
}

.overview-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.overview-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.overview-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 15px;
}

.overview-icon.total {
  background-color: #e3f2fd;
  color: #1976d2;
}

.overview-icon.active {
  background-color: #e8f5e8;
  color: #4caf50;
}

.overview-icon.draft {
  background-color: #fff3e0;
  color: #ff9800;
}

.overview-icon.expired {
  background-color: #ffebee;
  color: #f44336;
}

.overview-info {
  flex: 1;
}

.overview-number {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.overview-label {
  font-size: 14px;
  color: #666;
}

.query-card,
.toolbar-card,
.table-card {
  margin-bottom: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 15px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .cell) {
  padding: 0 8px;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}
</style>